const Upyun = require('../../utils/upyun-wxapp-sdk')
const upyun = new Upyun({
  bucket: 'feijiu-img5',
  operator: 'feijiu',
  getSignatureUrl: 'https://zsbpt.zaisubao.cn/index.php/Api/Feijiu/getSignature'
  // getSignatureUrl: 'https://v0.api.upyun.com'
})
let date = new Date;
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
const minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
const second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
const milliSeconds = date.getMilliseconds();
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {

    Type: 1,
    sourceType: ['camera', 'album'],
    sizeType: ['compressed'],
    YxDate: 0,
    YxDateCn: [{ name: '一个月', yx: 30 }, { name: '三个月', yx: 90 }, { name: '半年', yx: 180 }, { name: '一年', yx: 360 }, { name: '长期', yx: 0 }],
    CFFS_index: 0,
    CFFS: [{ name: '库存存放', yx: 0 }, { name: '露天存放', yx: 1 }],

    ProNum: 0,
    Title: '',
    count: 3,
    imageList: [],
    imageLists: [],
    addimgStatus: true,
    shidicon: ' icon-xiangxia',
    addrname: '全国',
    typename: '请选择信息分类',
    GQ_classid: 0,
    cityname: '请选择市',
    yxname: '一个月',
    p: 0,
    pindex: 0,
    city: 0,
    cindex: 0,
    FjLoginLog: wx.getStorageSync('FjLoginLog'),
    ComName: '',
    Linkman: '',
    Mobile: '',
    Description: '',
    vodurl: '',
    vodfm: '',
    is_vod: false,
    duration: '',
    XJCD: [{ name: '选择新旧程度', code: 0 }, { name: '9成新', code: 13 }, { name: '8成新', code: 6 }, { name: '7成新', code: 4 }, { name: '6成新', code: 2 }, { name: '5成新', code: 7, name: '库存', code: 15 }, { name: '已翻新', code: 16 }, { name: '不限', code: 17 }],
    XJCD_index: 0,
    IsGQVideo: 0,//是否能上传视频
    ProPrice: '',
    ProPriceStatus: false,
  },

  checkboxChange: function (e) {
    if (e.detail.value.length == 1) {
      this.setData({
        ProPrice: '电议或面议',
        ProPriceStatus: true
      })
    } else {
      this.setData({
        ProPrice: '',
        ProPriceStatus: false
      })
    }
    // console.log(e.detail.value.length)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.shid) {
      this.setData({
        Type: options.shid
      })

      if (options.shid == 1) {
        wx.setNavigationBarTitle({
          title: '发布供应信息'
        })
      } else {
        wx.setNavigationBarTitle({
          title: '发布求购信息'
        })
      }

    }
    if (app.checkFjLogin()) {
      this.setData({
        FjLoginLog: wx.getStorageSync('FjLoginLog')
      })
      var FjLoginLog = wx.getStorageSync('FjLoginLog');
      var that = this
      var api_input = {
        uid: FjLoginLog.UID,
        upwd: FjLoginLog.UPwd
      }
      app.getDaoPost('api/FeijiuApp/Post_FJ_UserInfoByUID', api_input, function (r) {
        var udata = JSON.parse(app.aesDec(r.data));
        console.log(udata);
        that.setData({
          ComName: udata.Uinfo[0].ComName,
          Linkman: udata.Uinfo[0].Linkman,
          Mobile: udata.Uinfo[0].Mobile,
          IsGQVideo: udata.IsGQVideo
        })
      })
    } else {
      wx.navigateTo({ url: '../../pages/login/index' });
    }
  },

  Proprice: function (e) {
    this.setData({
      ProPrice: e.detail.value
    })
  },
  /**
   * 上传视频
   * @return {[type]} [description]
   */
  choosevod: function () {
    if (this.data.IsGQVideo != 1) {
      app.tishi('本功能仅限VIP会员、旗舰会员、 尊享会员发布,您可以联系客服进行会员升级!'); return false;
    }
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success(r) {
        // console.log(r);return false;
        if (r.size > 10000000) {
          app.tishi('您上传的视频已超过10M!请缩小后再上传!'); return false;
        }
        var index = r.tempFilePath.lastIndexOf("\.");
        var kuozhan = r.tempFilePath.substring(index + 1, r.tempFilePath.length);
        var name = that.Appendzero(day) + '' + hour + '' + minute + '' + second + '' + milliSeconds + '' + that.threeRand() + '.' + kuozhan;
        var vodSrc = r.tempFilePath;
        wx.showLoading({
          title: "视频正在上传中"
        })
        upyun.upload({
          localPath: vodSrc,
          remotePath: '/video/product/' + year + '/' + that.Appendzero(month) + '/' + that.Appendzero(day) + '/' + name,
          success: function (res) {
            wx.showToast({
              title: '上传成功',
              icon: 'success',
              duration: 1000
            })
            if (res.statusCode == 200) {
              res.data = JSON.parse(res.data);
              if (res.data.code == 200) {
                that.setData({
                  vodurl: res.data.url,
                  vodfm: r.thumbTempFilePath,
                  is_vod: true,
                  duration: that.formatTime(Math.round(r.duration))
                })

              } else {
                app.tishi('视频上传失败,请重试!')
              }

            } else {
              app.tishi('视频上传失败,请重试!')
            }
          },
          fail: function ({ errMsg }) {
            console.log('uploadImage fail, errMsg is', errMsg)
          },
        })
      }
    })
  },
  bindPickerChange: function (e) {
    this.setData({
      XJCD_index: e.detail.value
    })
  },

  changeProvince: function () {
    wx.navigateTo({
      url: 'selectProvince?pindex=' + this.data.pindex
    })
  },

  changeCity: function () {
    wx.navigateTo({
      url: 'selectCity?pindex=' + this.data.pindex + '&cindex=' + this.data.cindex
    })
  },
  getClass: function () {
    wx.navigateTo({
      url: 'GqClassList'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  chooseImage: function (e) {
    var that = this
    wx.chooseImage({
      sourceType: this.data.sourceType,
      sizeType: this.data.sizeType,
      count: this.data.count,
      success: function (res) {
        var resultArr = res.tempFilePaths;
        var imageListArr = that.data.imageList;
        for (var i = 0; i < resultArr.length; i++) {
          wx.uploadFile({
            url: app.data.api_url + 'api/FeijiuApp/GqImageUpload?strRSA=' + app.data.strRSA,
            filePath: resultArr[i],
            name: 'file',
            success: function (info) {
              imageListArr.push(JSON.parse(info.data));
              that.checkImgNum(imageListArr)
              that.setData({
                imageList: imageListArr,
                count: 3 - imageListArr.length
              })
            }
          })
        }
      }
    })


  },

  uploadImg: function (url) {
    var that = this
    api_input = {
      img: url
    }
  },

  checkImgNum: function (arr) {
    if (arr.length >= 3) {
      this.setData({
        addimgStatus: false
      })
    } else {
      this.setData({
        addimgStatus: true
      })
    }
  },
  imageDel: function (e) {
    var ind = e.currentTarget.dataset.ind;
    var list = this.data.imageList;
    list.splice(ind, 1)
    this.setData({
      imageList: list
    })
    this.checkImgNum(this.data.imageList)
  },
  applyName: function (e) {
    this.setData({
      Title: e.detail.value
    })
  },
  ProNum: function (e) {
    this.setData({
      ProNum: e.detail.value
    })
  },
  changeYx: function (e) {
    this.setData({
      YxDate: e.currentTarget.dataset.yx
    })
  },

  changeCFFS: function (e) {
    this.setData({
      CFFS_index: e.currentTarget.dataset.yx
    })
  },
  applyContens: function (e) {
    this.setData({
      Description: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },

  checkInput: function (tishi) {
    wx.showModal({
      title: 'Feijiu网提示您',
      content: tishi,
      showCancel: false,
      confirmText: '确定',
      confirmColor: '#3CC51F'
    })
  },
  //三张图片合拼成,分开的字符串
  picJoin: function (arr) {
    var pic = '';
    for (var i = 0; i < arr.length; i++) {
      if (i == arr.length - 1) {
        pic += arr[i][0];
      } else {
        pic += arr[i][0] + '|';
      }
    }
    return pic;
  },
  processAddr: function (pr, ct) {
    var addres = '';
    if (ct == '请选择市') {
      addres = pr;
    } else {
      addres = pr + ct
    }
    return addres
  },
  gongqiuFb: function () {
    if (this.data.Title.length < 1) {
      app.tishi('请输入您的信息标题')
      return false;
    }
    if (this.data.ProNum <= 0) {
      app.tishi('请输入您的产品数量')
      return false;
    }
    if (this.data.GQ_classid == 0) {
      app.tishi('请选择信息分类')
      return false;
    }
    if (this.data.Description.length < 1) {
      app.tishi('产品描述不能为空,请输入')
      return false;
    }
    if (this.data.ProPrice.length < 1) {
      app.tishi('请输入产品价格,或选择电议或面议!')
      return false;
    }
    if (this.data.XJCD[this.data.XJCD_index].code == 0) {
      app.tishi('请选择新旧程度!')
      return false;
    }
    var that = this;

    var strInfoJson = {
      LoginUID: this.data.FjLoginLog.UID,//登录用户ID，
      gqid: 0,
      Video: app.data.vodurl + this.data.vodurl,
      Title: this.data.Title,
      Description: this.data.Description,
      Type: this.data.Type,
      Photo: this.picJoin(this.data.imageList),
      YxDate: this.data.YxDate,
      ProXh: '',
      ProNum: this.data.ProNum,
      ProAddress: this.processAddr(this.data.addrname, this.data.cityname),
      ProPrice: this.data.ProPrice,
      ClassId: this.data.GQ_classid,
      ProClass: this.data.typename,
      Province: this.data.p,
      XJCD: this.data.XJCD[this.data.XJCD_index].code,
      city: this.data.city,
      CFFS: this.data.CFFS[this.data.CFFS_index].name,
      PP: '',
      platform_type: 4
    }
    app.getDaoPost('api/FeijiuApp/Feijiu_Add_GqInfo', strInfoJson, function (r) {
      console.log(r)
      if (r.code == 200) {
        if (r.data.IsSuccess == 1) {
          wx.navigateTo({
            url: 'fbSuccess?shid=' + that.data.Type
          })
        } else if (r.data.IsSuccess == -1) {
          that.checkInput('您今天已经发布过相同的信息了,请不要重复提交');
        } else {
          that.checkInput('发布失败,请联系客服人员或者人工发布');
        }
      } else {
        app.tishi(r.message);
      }
    })
    // console.log(strInfoJson);return false;
    // var api_input = {
    //   company:this.data.ComName,
    //   LinkMen:this.data.Linkman,
    //   mobilephone:this.data.Mobile,
    //   strRSA:app.data.strRSA,
    //   strInfoJson:JSON.stringify(strInfoJson),
    //   userpwd:this.data.FjLoginLog.UPwd
    // }
    // var that = this;
    // app.getDaoPostOld('api/FeijiuApp/Add_FabuGq',api_input,function (r) {
    //   if (r.code == 200) {
    //     if (r.data.IsSuccess == 1) {
    //       wx.navigateTo({
    //         url: 'fbSuccess?shid='+that.data.Type
    //       })
    //     }else if (r.data.IsSuccess == -1) {
    //       that.checkInput('您今天已经发布过相同的信息了,请不要重复提交');
    //     }else{
    //       that.checkInput('发布失败,请联系客服人员或者人工发布');
    //     }        
    //   }else{
    //     app.tishi(r.message);

    //   }

    // })
    // Feijiu_Add_GqInfo

  },

  Appendzero: function (obj) {
    if (obj < 10) return "0" + "" + obj;
    else return obj;
  },
  threeRand: function () {
    var rand = "";
    for (var i = 0; i < 3; i++) {
      var r = Math.floor(Math.random() * 10);
      rand += r;
    }
    return rand;
  },
  formatTime: function (seconds) {
    let hour = Math.floor(seconds / 3600) >= 10 ? Math.floor(seconds / 3600) : '0' + Math.floor(seconds / 3600);
    seconds -= 3600 * hour;
    let min = Math.floor(seconds / 60) >= 10 ? Math.floor(seconds / 60) : '0' + Math.floor(seconds / 60);
    seconds -= 60 * min;
    let sec = seconds >= 10 ? seconds : '0' + seconds;
    return min + ':' + sec;
  }


})